import React, { Component } from 'react';
import './App.css';
import data from './data.json';

class App extends Component {

  state = {
    dl: data.list,
    ww: 1020,
    list: []
  }


  componentWillMount() {
    // this.gramer();
    this.renner();
  }

  // 固定 6 列
  gramer() {
    const cml = 6;
    const ww = 1020;
    const lmt = ww/cml;

    let catcharr = [];
    let list = [];

    this.state.dl.forEach((v, i) => {
      v.width = lmt*v.width/v.height
      v.height = lmt

      catcharr.push(v)

      if ((i + 1)%cml === 0) {
        let lr = catcharr.reduce((res, t) => (res.width || res) + t.width);
        let bl = lr/ww;

        list = list.concat(catcharr.map(item => {
          item.width = item.width/bl;
          item.height = item.height/bl;
          return item
        }))

        catcharr = [];
      }

      if (i === (this.state.dl.length - 1)) {
        list = list.concat(catcharr)
      }
    })

    this.setState({ list: JSON.parse(JSON.stringify(list)) })
  }

  renner() {
    const cml = 3;
    const ww = 1020;
    const lmt = ww/cml;
    const row = this.state.dl.length/cml >> 0;

    let catcharr = [];
    let list = [];

    let clist = this.state.dl.map(v => {
      v.width = lmt*v.width/v.height
      v.height = lmt
      return v
    })

    let lr = clist.reduce((res, t, i, arr) => {
      if (arr.length - arr.length%cml === i) {
        return res
      }
      return (res.width || res) + t.width
    });

    let aw = 0;
    clist.forEach((v, i) => {
      catcharr.push(v)
      aw+= v.width

      if (aw >= (lr/row - 50)) {
        let bl = aw/ww;

        list = list.concat(catcharr.map(item => {
          item.width = item.width/bl;
          item.height = item.height/bl;
          return item
        }))

        catcharr = [];
        aw = 0;
      }

      if (i === (clist.length - 1)) {
        list = list.concat(catcharr)
      }

    })

    this.setState({ list: JSON.parse(JSON.stringify(list)) })
  }


  render() {
    return (
      <div className="App">

        <div className="box">
          {
            this.state.list.map(v => (
              <div className="item"
                style={{
                  width: v.width || '100px',
                  height: v.height || '100px',
                  backgroundImage: `url(${v.equalh_url})`
                }}
                key={v.id}>
              </div>
            ))
          }
        </div>

      </div>
    );
  }
}

export default App;
